package server;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * 自定义类加载器
 */
public class MyClassLoader extends ClassLoader {

    public Class<?> findClass(String filePath, String name) {
        try {
            String[] split = name.split("\\.");
            String path = filePath + File.separator;
            for (String s : split) {
                path = path+File.separator+s;
            }
            path+=".class";
            FileInputStream in = new FileInputStream(path);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buf = new byte[1024] ;
            int len = -1 ;
            while((len = in.read(buf)) != -1){
                baos.write(buf , 0 , len);
            }
            in.close();
            byte[] classBytes = baos.toByteArray();
            return defineClass(classBytes , 0 , classBytes.length) ;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
